package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.comon.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.service.EmployeeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    //处理登录
    @PostMapping("/employee/login")
    public ResultInfo<Employee> login(HttpSession session, @RequestBody Employee employee) {

        //调用Service查询
        ResultInfo<Employee> resultInfoLogin = employeeService.login(employee);
        //将登陆信息传到Session中
        if (resultInfoLogin.getCode() == 1) {
            Employee employeeSession = resultInfoLogin.getData();
            session.setAttribute("SESSION_LOGIN", employeeSession);
        }
        //返回结果
        return resultInfoLogin;
    }

    //退出
    @PostMapping("/employee/logout")
    public ResultInfo<Object> logout(HttpSession session) {
        //清空Session中的内容
        session.invalidate();
        return ResultInfo.success(null);
    }

    //查询所有或者根据name查询
    @GetMapping("/employee/find")
    public ResultInfo<List<Employee>> findAllAndByName(String name) {
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(name),
                Employee::getName, name);
        //查询
        List<Employee> allAndByName = employeeService.list(wrapper);
        //返回结果
        return ResultInfo.success(allAndByName);
    }

    //添加员工
    @PostMapping("/employee")
    public ResultInfo save(@RequestBody Employee employee) {
        employeeService.insert(employee);
        return ResultInfo.success(null);
    }

    //根据id查询
    @GetMapping("/employee/{id}")
    public ResultInfo findById(@PathVariable("id") Long id) {
        Employee em = employeeService.getById(id);
        return ResultInfo.success(em);
    }

    //修改
    @PutMapping("/employee")
    public ResultInfo updateById(@RequestBody Employee employee) {
        employeeService.updateById(employee);
        return ResultInfo.success(null);
    }
}
